const App = getApp()
import { HomeModel } from '../../models/home.js'
import { AppModel } from '../../models/app.js'
import { MineModel } from '../../models/mine'
import { CouponModel } from '../../models/coupon'
import { ManagerModel } from '../../models/manager'
// import { SeckillModel } from '../../models/seckill'
const managerModel = new ManagerModel()
const mineModel = new MineModel()
const ModelHome = new HomeModel()
const ModelApp = new AppModel()
const ModelCoupon = new CouponModel()
// const ModelSeckill = new SeckillModel()
Page({
  data: {
    isLogined: true,
    bossid: '', // 分享人
    pageIndex: 1, // 分页参数
    pageSize: 10, // 分页参数
    loading: false, // 锁
    hasNext: true, // 下一页
    specialList: [], // 专场列表
    showShare: false,
    showType: '',
    shareData: {},
    authBanner: [
      {
        bannerType: 7,
        id: 'aae01e58bf294e1dbee6fe34be60360a',
        bannerImg: 'https://imgs.top1buyer.com/admin/marketing/marketing_img_20190829141245464.jpg'
      },
      {
        bannerType: 7,
        id: 'c3068077cdb1407a80df860c323af640',
        bannerImg: 'https://imgs.top1buyer.com/admin/marketing/marketing_img_20190829141158690.jpg'
      },
      {
        bannerType: 7,
        id: '2d244613490d4d9681a9b1e7851b8c50',
        bannerImg: 'https://imgs.top1buyer.com/admin/marketing/marketing_img_20190829141118559.jpg'
      },
      {
        bannerType: 7,
        id: 'c9cbbc8c322b4962a2f7ea426f1e3a40',
        bannerImg: 'https://imgs.top1buyer.com/admin/marketing/marketing_img_20190829141057259.jpg'
      }
    ],
    bigBanner: [], // 大轮播
    minBanner: [], // 小轮播
    classifyBanner: [], // 分类轮播
    redid: '',
    showNewRed: false,
    showService: false,
    serviceInfo: {},
    indexBanner: '',
    ruleDetail: null, // 1 审核中 0 不审核
    iphoneX: App.globalData.isIphoneX,
    damoHeight: '407',
    // specialListArray: [],
    bindPhone: false,
    userType: '',
    code: '',
    logoList: [],
    showCoupon: false,
    couponList: [],
    showRedrain: false,
    redRainTime: '', //倒计时
    reaRainCount: {},
    rainTime: 3,
    guideVisible: false,
    guideInfo: {},
    isBackRed: true,
    wiggle: true,
    comeBack: false,
    showCard: false,
    statusBarHeight: App.globalData.statusBarHeight,
    isFocusOn: true,
    bindPhoneVisible: false, // 显示绑定手机
    ready: false,
    // seckillInfo: {}, // 好物快抢
    // seckillDate: '', // 好物快抢时间
    showGuide: false, //邀粉福利
    brandsPopupVisible: false, // 左侧导航栏
    naviList: [],
    activeNav: {},
    activeNavIndex: 0
  },
  onLoad: function(options) {
    console.log('home onLoad=', options)
    // 通过二维码进入
    if (options.scene) {
      let scene = decodeURIComponent(options.scene)
      // &是我们定义的参数链接方式
      this.data.bossid = scene.split('&')[0]
    } else {
      // 页面分享进入
      this.data.bossid = options.bossid // 分享人id
    }
    // 存储bossid
    wx.setStorageSync('bossid', this.data.bossid)
    // 获取环境变量
    this.queryEnv()
    // 获取轮播图
    this.getClassifyBanner()
    // 隐藏右上角分享功能
    wx.hideShareMenu()
    // 初始化
    this.init()
  },
  // 用户登录
  init() {
    const _this = this
    App.getVipInfo(function(userInfo) {
      if (!userInfo) {
        console.log('没有token,获取用户信息失败isLogined=', _this.data.isLogined)
        _this.setData({
          isLogined: false
        })
        // 进入页面
      } else {
        // 用户操作,绑定手机，新手红包
        _this._userEvent()
        // 获取头部滚动标签，然后请求列表
        _this.getLabelList()
        // 获取粉丝
        _this.getFans()
      }
    })
  },
  // 登陆成功，由login组件触发
  loginSuccess() {
    this.setData({
      isLogined: true
    })
    // 成功后操作
    this._userEvent()
    // 获取头部滚动标签，然后请求列表
    this.getLabelList()
    // 获取粉丝
    this.getFans()
  },
  // 获取滚动标签，然后请求列表
  getLabelList() {
    ModelHome.getNaviList().then(res => {
      this.setData({
        naviList: res.data.naviList,
        activeNav: res.data.naviList[0]
      })
      // 获取专场列表
      this.loadMore(true)
    })
  },
  // 用户操作,绑定手机，新手红包
  _userEvent() {
    const _this = this
    const userInfo = App.globalData.userInfo
    // 绑定手机实时获取code，防止失效
    wx.login({
      success: function(res) {
        if (res.code) {
          //发起网络请求
          _this.setData({
            code: res.code
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    })
    // 新用户发红包
    if (userInfo.isActive == 1) {
      // 显示红包弹框 传红包id
      _this.setData({
        redid: userInfo.redId,
        showNewRed: true
      })
    }
    // 如果是黄金和黑金绑定手机号
    if (userInfo.userType == 2 || userInfo.userType == 3) {
      if (!userInfo.userPhone || userInfo.userPhone == 0) {
        _this.setData({
          bindPhone: true,
          userType: Number(userInfo.userType)
        })
      }
    }
    //查询优惠券信息
    _this.SelectCoupon()
    //红包雨
    _this.redPacketRain()
    //右上角显示关注信息
    const homefocus = wx.getStorageSync('homefocus')
    if (homefocus) {
      _this.setData({
        isFocusOn: false
      })
    } else {
      _this.setData({
        isFocusOn: true
      })
    }
    //获取好物快抢
    // _this.selectIndexSeckill()
  },
  // 获取环境变量`
  queryEnv() {
    let _this = this
    // 如果已经请求到了数据
    if (App.globalData.ruleDetail) {
      _this.setData({
        ruleDetail: App.globalData.ruleDetail
      })
      // 没有的话设置回调
    } else {
      App.queryEnvCb = res => {
        _this.setData({
          ruleDetail: res
        })
      }
    }
  },
  //查询优惠券信息
  SelectCoupon() {
    const self = this
    const params = {}
    ModelCoupon.selectActivityCoupon(params)
      .then(res => {
        if (res.data.couponList.length > 0) {
          self.setData({
            showCoupon: true,
            couponList: res.data.couponList
          })
        }
      })
      .catch(err => {
        App.globalData.bug.notifyError(JSON.stringify(err))
      })
  },
  //跳转搜索页面
  tapToSearch() {
    wx.navigateTo({
      url: '/pages/search/index'
    })
  },
  //红包雨
  redPacketRain: function() {
    const self = this
    self.redrain = this.selectComponent('#redrain')
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    const params = {}
    self.setData({
      reaRainCount: {}
    })
    //判断在首页
    if (currentPage.route == 'pages/home/index') {
      ModelApp.redRain(params)
        .then(res => {
          // const { sign3, startTime } = res.data
          //判断活动中,并且有下一场显示，startTime 下一场的时间 为0没有下一场
          self.setData({
            reaRainCount: res.data // 更新数据
          })
          // 判断是否可以进入红包雨页面，并且未领取领取过
          if (res.data.sign == 1 && res.data.sign2 == 0) {
            self.setData({
              showRedrain: true,
              rainTime: 3
            })
            self.redrain.timeout()
          }
          // self.setData({
          //   reaRainCount: res.data
          // })
          // {"data":{"sign2":1,"sign3":1,"sign":1,"startTime":0,"dateNow":1568188431000},"status":200,"info":"success"}

          // if (res.data.sign3 == 1) {
          //   // 判断下雨中
          //   if (res.data.sign == 1) {
          //     // 判断未领取过
          //     if (res.data.sign2 == 0) {
          //       self.setData({
          //         showRedrain: true,
          //         rainTime: 3
          //       })
          //       self.redrain.timeout()
          //     }
          //   }
          // }
        })
        .catch(err => {
          App.globalData.bug.notifyError(JSON.stringify(err))
        })
    }
  },
  //关闭优惠券
  closeCouponList(e) {
    const params = {}
    ModelCoupon.activateCoupon(params)
      .then(res => {})
      .catch()
    this.setData({
      showCoupon: e.detail
    })
  },
  //获取分类
  getClassifyBanner() {
    const self = this
    const params = {}
    ModelHome.getBannerList(params)
      .then(res => {
        const classList = res.data.classList
        // 分类需要分组
        var result = []
        // 分组
        for (var i = 0, len = classList.length; i < len; i += 2) {
          result.push(classList.slice(i, i + 2))
        }
        self.setData({
          //  bigBanner: res.data.bannerList, // 大轮播
          // minBanner: res.data.minBannerList, // 小轮播
          classifyBanner: result // 分类轮播
        })
      })
      .catch(err => {
        console.log(err)
      })

    //查询最后疯抢
    ModelHome.queryCrazy()
      .then(res => {
        self.setData({
          minBanner: res.data.classList
        })
      })
      .catch()
  },
  // 组件触发显示售后
  showService() {
    const _this = this
    App.queryServiceInfo(function(serviceInfo) {
      _this.setData({
        showService: true,
        serviceInfo: serviceInfo
      })
    })
  },
  // 点击分享
  shareActivity(event) {
    const shareInfo = event.detail.activity
    const type = event.detail.type
    // 设置分享
    this.setShareNum(shareInfo.id)
    // 预告
    if (type == 1) {
      // 开启预告状态
      if (shareInfo.specialOpen) {
        this.setData({
          showShare: true,
          showType: 'preactivity',
          shareData: {
            specialCode: shareInfo.specialCode,
            shareTitle: shareInfo.specialName,
            mainImg: shareInfo.mainImg,
            shareImg: shareInfo.shareImg + '?imageMogr2/quality/80',
            startDate: shareInfo.startDate,
            endDate: shareInfo.endDate,
            sharePath: `/pages/trailer/index?bossid=${App.globalData.userInfo.userCode}&scode=${shareInfo.specialCode}`
          }
        })
      } else {
        this.setData({
          showShare: true,
          showType: 'preactivitytohome',
          shareData: {
            specialCode: shareInfo.specialCode,
            shareTitle: shareInfo.specialName,
            mainImg: shareInfo.mainImg,
            shareImg: shareInfo.shareImg + '?imageMogr2/quality/80',
            startDate: shareInfo.startDate,
            endDate: shareInfo.endDate,
            sharePath: `/pages/home/index?bossid=${App.globalData.userInfo.userCode}` // 开个关闭的时候分享首页
          }
        })
      }
    } else {
      // 活动中
      this.setData({
        showShare: true,
        showType: 'activity',
        shareData: {
          shareTitle: shareInfo.specialName,
          mainImg: shareInfo.mainImg,
          shareImg: shareInfo.shareImg + '?imageMogr2/quality/80',
          startDate: shareInfo.startDate,
          endDate: shareInfo.endDate,
          specialCode: shareInfo.specialCode,
          sharePath: `/pages/activity/index?bossid=${App.globalData.userInfo.userCode}&scode=${shareInfo.specialCode}`
        }
      })
    }
  },
  // 统计分享数量
  setShareNum(id) {
    ModelApp.addShare({
      specialId: id
    })
      .then(res => {})
      .catch()
  },
  //加载更多
  loadMore(reload) {
    if (reload) {
      this.setData({
        pageIndex: 1,
        hasNext: true
      })
    }

    if (this.data.loading || !this.data.hasNext) {
      return
    }
    this.setData({
      loading: true
    })

    const params = {
      // type: this.data.type,
      id: this.data.activeNav.id,
      isBar: this.data.activeNav.isBar, // 签标示：0普通专场标签，1 预告专场 2：活动中专场 (必传字段)
      pageIndex: this.data.pageIndex,
      pageSize: this.data.pageSize
    }
    // 请求数据
    ModelHome.getActivity(params)
      .then(res => {
        // 如果重新加载则清空
        if (reload) {
          this.setData({
            specialList: [],
            bigBanner: []
          })
          if (res.banner.bannerList) {
            this.setData({
              bigBanner: res.banner.bannerList // 大轮播
            })
          }
        }
        const tempArray = this.data.specialList.concat(res.data.specialList)
        this.setData({
          specialList: tempArray,
          hasNext: res.data.hasNext,
          loading: false,
          ready: true
        })
        wx.stopPullDownRefresh()
      })
      .catch(err => {
        this.setData({
          loading: false
        })
      })
  },
  onReachBottom: function() {
    if (!this.data.isLogined) {
      return
    }
    // 微信到底
    this.data.pageIndex = this.data.pageIndex + 1
    this.loadMore()
  },
  // 转发
  onShareAppMessage: function(ops) {
    const that = this
    // const ucode = wx.getStorageSync('ucode')
    const ucode = App.globalData.userInfo.userCode
    console.log('home onShareAppMessage ucode====' + ucode)
    if (ops.from === 'button') {
      // 来自页面内转发按钮
      const shareInfo = ops.target.dataset.share
      console.log(shareInfo)
      that.path = shareInfo.sharePath
      that.title = shareInfo.shareTitle
      that.img = shareInfo.shareImg
    } else if (ops.from === 'menu') {
      that.title = '小蚁买手'
      that.path = `/pages/home/index?bossid=${ucode}`
      that.img = ''
    }
    console.log(that.path)
    return {
      title: that.title,
      path: that.path,
      imageUrl: that.img,
      success: function(res) {
        // 转发成功
        console.log('转发成功:' + JSON.stringify(res))
      },
      fail: function(res) {
        // 转发失败
        console.log('转发失败:' + JSON.stringify(res))
      }
    }
  },
  // 下拉刷新
  onPullDownRefresh: function() {
    if (!this.data.isLogined) {
      //停止下拉刷新
      wx.stopPullDownRefresh()
      return
    }
    // 全部的时候刷新
    if (this.data.activeNavIndex == 0) {
      this.getLabelList()
      // 获取轮播图
      this.getClassifyBanner()
      // 重置
      this.setData({
        showCoupon: false
      })
      //获取优惠券
      this.SelectCoupon()
      //获取好物快抢
      //  this.selectIndexSeckill()
      //查询红包雨时间
      this.redPacketRain()
    }
    //  请求列表
    this.loadMore(true)
    //停止下拉刷新
    wx.stopPullDownRefresh()
  },
  //预览专场
  onTap(e) {
    const item = e.currentTarget.dataset.item
    // 如果预告已经开启
    if (item.specialOpen) {
      wx.navigateTo({
        url: `/pages/trailer/index?scode=${item.specialCode}`
      })
    }
  },
  // 预约专场
  trailerActivity: function(e) {
    //判断是否绑定手机号
    const self = this
    const index = e.currentTarget.dataset.index
    const userInfo = App.globalData.userInfo
    if (!userInfo.userPhone || userInfo.userPhone == 0) {
      //未绑定手机号，弹出授权提示
      self.setData({
        ifName: true
      })
    } else {
      //已绑定手机号
      const params = {
        specialId: e.currentTarget.dataset.code
      }
      ModelApp.selectAppointment(params)
        .then(res => {
          self.data.specialList[index].specialStatus = 1
          self.setData({
            specialList: self.data.specialList
          })
          App.WxService.showToast({
            title: '预约成功',
            icon: 'none'
          })
        })
        .catch()
    }
  },
  // 扫码查价
  scan() {
    wx.scanCode({
      success: res => {
        wx.navigateTo({
          url: `/pages/home/scan/index?gbCode=${res.result}`
        })
      },
      fail: res => {
        wx.showToast({
          title: '扫码失败',
          icon: 'success',
          duration: 2000
        })
      },
      complete: res => {}
    })
  },
  // 取消
  cancel: function() {
    this.setData({
      type: 1
    })
    this.loadMore(true)
  },
  // 点击触发显示新手指导
  emitShowGuide() {
    // 停止晃动
    this.setData({
      wiggle: false
    })
    // 普通用户弹出新手导航
    if (this.data.userType == 1) {
      // this.setData({
      //   guideVisible: false
      // })
      this.emitShareGuide()
    } else {
      // 其他用户弹出分享
      this.emitShareGuide()
    }
  },
  // 停止分享icon晃动
  doStopWiggle() {
    this.setData({
      wiggle: true
    })
  },
  // 获取粉丝
  getFans() {
    //获取当前用户类型，佣金，粉丝，邀请人信息
    managerModel
      .getFansInfo()
      .then(res => {
        // 获取还有多少粉丝升级
        const guideInfo = res.data
        guideInfo.userImg = App.globalData.userInfo.userImg
        this.setData({
          userType: res.data.userType,
          guideInfo: guideInfo
        })
        if (res.data.userType == 1) {
          // 普通用户分享
          this.showSharePop()
        }
      })
      .catch(err => {})
  },
  // 触发首页分享
  emitShareGuide() {
    // 获取分享图
    mineModel
      .queryrule({
        ruleType: '018'
      })
      .then(res => {
        // 图片以逗号分隔
        const homeShareImages = res.data.rule.ruleDetail.split(',')
        const userInfo = App.globalData.userInfo
        this.setData({
          showType: 'index',
          showShare: true,
          wiggle: false,
          shareData: {
            shareTitle: ` ${decodeURIComponent(userInfo.nickName)} 邀您加入小蚁买手`,
            sharePath: `/pages/home/index?bossid=${userInfo.userCode}`,
            shareImg: homeShareImages[0] + '?imageMogr2/quality/80',
            shareHomeImg: homeShareImages[1] + '?imageMogr2/quality/80'
          }
        })
      })
  },
  onHide: function() {
    this.setData({
      comeBack: true
    })
  },
  // 预约
  doSubscribe() {
    this.setData({
      bindPhoneVisible: true
    })
  },
  //查询首页秒杀商品
  selectIndexSeckill() {
    const that = this
    const params = {}
    let seckillDate = that.data.seckillDate
    ModelSeckill.selectIndexSeckill(params)
      .then(res => {
        that.setData({
          seckillDate: ''
        })
        if (res.data.indexSeckill) {
          if (res.data.indexSeckill.status == 1) {
            seckillDate = res.data.indexSeckill.startDate
          } else if (res.data.indexSeckill.status == 2) {
            seckillDate = res.data.indexSeckill.endDate
          }
          that.setData({
            seckillDate: seckillDate,
            seckillInfo: res.data.indexSeckill
          })
        } else {
          that.setData({
            seckillInfo: {}
          })
        }
        that.seckill = this.selectComponent('#seckill')
        that.seckill.countDown(seckillDate)
      })
      .catch()
  },
  // 分享弹窗
  showSharePop() {
    if (App.globalData.levelFlag) {
      this.setData({
        showGuide: true
      })
      App.globalData.levelFlag = false
    }
  },
  // 侧滑栏
  doShowBrands() {
    this.setData({
      brandsPopupVisible: true
    })
  },
  showAllNav() {
    this.setData({
      showNav: !this.data.showNav
    })
  },
  //选择滚动栏标签
  chooseNav(e) {
    //设置当前样式
    this.setData({
      activeNav: e.detail.item,
      activeNavIndex: e.detail.index
    })
    this.loadMore(true)
  }
})
